#! /usr/bin/env python
#coding=utf-8
#author: sixther.me
import time,os
import urllib
import urllib2
import cookielib
import MySQLdb
import smtplib
import time
from email.mime.text import MIMEText
 
current_time=time.strftime('%Y-%m-%d %H %A',time.localtime(time.time()))
end_time=time.strftime('%Y-%m-%d %H',time.localtime(time.time()))
screens = ["Online Sales (30min)"]
save_graph_path = "/usr/share/zabbix/reports/%s"%time.strftime("%Y-%m-%d")
if not os.path.exists(save_graph_path):
    os.makedirs(save_graph_path)
# zabbix host
zabbix_host = "monitor.xxx.me"
# zabbix login username
username = "xxxxxxxx"
# zabbix login password
password = "xxxxxx"
# graph width
width = 800
# graph height
height = 150
# graph Time period, s
period = 86400
# zabbix DB
dbhost = "10.2.2.2"
dbport = 3306
dbuser = "zabbix"
dbpasswd = "xxxxxxxxx"
dbname = "zabbix"
# mail
to_list = ["duanchao@lightinthebox.com"]
smtp_server = "smtp.exmail.qq.com"
smtp_port = 25
mail_user = "ops_monitor@lightinthebox.com"
mail_pass = "xxxxxxxx"

zabbix_conn=MySQLdb.connect(host=dbhost,user=dbuser,passwd=dbpasswd,db=dbname,charset='utf8')

def fetch_one_sql(sql): 
    zabbix_cursor=zabbix_conn.cursor()
    zabbix_cursor.execute(sql)
    result='%s' % zabbix_cursor.fetchone()
    zabbix_cursor.close()
    return result
def fetch_list_sql(sql):
    zabbix_cursor=zabbix_conn.cursor()
    zabbix_cursor.execute(sql)
    result=zabbix_cursor.fetchall()
    zabbix_cursor.close()
    return result
def get_graph(zabbix_host,username,password,screen,width,height,period,save_graph_path):
    global html
    css='''
<style type='text/css'>
div#container{background-color:#C0C0C0;width:100%;text-align:center;}
div#header {background-color:#C0C0C0;text-align:left}
div#image {text-align:center;}
div#footer {background-color:#708090;clear:both;text-align:left;}
</style>
'''
    html="<html>" + css + "<div id='container'><div id='header'><strong>The following data ended in " + end_time  + ",and began in yestoday at the same period .<br>The Data Include:</strong><br><small>&nbsp&nbsp&nbsp&nbspThe Number of Total Order(Litb/Mini)<br>&nbsp&nbsp&nbsp&nbspThe Number of Individual Site Order(PC/Mobile/APP)<br>&nbsp&nbsp&nbsp&nbspThe Number of Individual Language Order<br>&nbsp&nbsp&nbsp&nbspThe Number of Individual Payment Order</small><br><strong>Data Source: Online Database</strong><br><br></div>"
    screenid_list = []
    screenid=fetch_one_sql("select screenid from screens where name='%s'"%(screen))
    graphid_list = []
    for c in fetch_list_sql("select resourceid from screens_items where screenid='%s' order by y,x"%(int(screenid))):
        for d in c:
            graphid_list.append(int(d))
    for graphid in graphid_list:
        login_opt = urllib.urlencode({
            "name": username,
            "password": password,
            "autologin": 1,
            "enter": "Sign in"})
        get_graph_opt = urllib.urlencode({
            "graphid": graphid,
            "screenid": screenid,
            "width": width,
            "height": height,
            "period": period})
        cj=cookielib.CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        login_url = r"http://%s/index.php"%zabbix_host
        save_graph_url = r"http://%s/chart2.php"%zabbix_host
        opener.open(login_url,login_opt).read()
        data = opener.open(save_graph_url,get_graph_opt).read()
        filename = "%s/%s.%s.png"%(save_graph_path,screenid,graphid)
        html += "<div id='image'><img width='800' height='350' src='http://%s/%s/%s/%s.%s.png'><br><br></div>"%(zabbix_host,save_graph_path.split("/")[len(save_graph_path.split("/"))-2],save_graph_path.split("/")[len(save_graph_path.split("/"))-1],screenid,graphid)
        f = open(filename,"wb")
        f.write(data)
        f.close()
def send_mail(recipient,subject,mail_body):
    msg='''From:BUDDY@lightinthebox.com
To:%(recipient)s
Subject:%(subject)s
Content-type: text/html

%(mail_body)s
'''
    sendmsg=msg % dict(recipient=recipient,subject=subject,mail_body=mail_body)
    server = smtplib.SMTP()
    server.connect(smtp_server,smtp_port)
    server.login(mail_user,mail_pass)
    server.sendmail(mail_user,recipient,sendmsg)
if __name__ == '__main__':
    for screen in screens:
        get_graph(zabbix_host,username,password,screen,width,height,period,save_graph_path)
    footer="<div id='footer'>Supported by &reg&nbspLITB_OPS&nbsp&nbsp&nbsp&nbsp<a href='mailto:ops_china@lightinthebox.com'>contact us</a><br>This message was sent by Zabbix.</div>"
    html=html + footer + "</div></body></html>"
    send_mail(to_list,"LITB monitoring report   " + current_time + "  (PST)",html)
